/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: OtcBuyPresenter.java
 *   @Date: 19-1-18 下午4:43
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2019 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.otc.presenter;

import android.content.Intent;
import android.text.TextUtils;

import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import io.bhex.app.base.AppUI;
import io.bhex.app.utils.IntentUtils;
import io.bhex.app.utils.NumberUtils;
import io.bhex.baselib.core.SPEx;
import io.bhex.baselib.mvp.BaseCoreActivity;
import io.bhex.baselib.mvp.BasePresenter;
import io.bhex.baselib.network.Utils.CodeUtils;
import io.bhex.baselib.network.listener.SimpleResponseListener;
import io.bhex.baselib.network.response.ResultResponse;
import io.bhex.sdk.account.UserInfo;
import io.bhex.sdk.otc.OtcApi;
import io.bhex.sdk.otc.OtcConstant;
import io.bhex.sdk.otc.OtcMessageApi;
import io.bhex.sdk.otc.OtcOrderApi;
import io.bhex.sdk.otc.bean.OrderPendingCountResponse;
import io.bhex.sdk.otc.bean.OrderPendingListResponse;
import io.bhex.sdk.otc.bean.OtcConfigResponse;
import io.bhex.sdk.otc.bean.OtcMessageResponse;
import io.bhex.sdk.otc.bean.OtcOrderInfoResponse;

public class OtcBuyPresenter extends BasePresenter<OtcBuyPresenter.OtcBuyUI> {
    private String orderId;
    private Timer timer;
    private TimerTask timerTask;

    public void goOrderAppeal() {
        if (TextUtils.isEmpty(orderId)) {
            return;
        }
        IntentUtils.goOtcOrderAppeal(getActivity(),orderId);

    }

    public interface OtcBuyUI extends AppUI{

        void showOrderInfo(boolean isAutoReq, OtcOrderInfoResponse response);

        void showCancelOrderSuccess();

        void showComfirmOrderPaySuccess();

        void showHasMessage(boolean isHasMessage);

        void showBankList(List<OtcConfigResponse.BankBean> bankList);

        void showIsShowRiskTips(boolean isShowRiskTips);
    }

    @Override
    public void onUIReady(BaseCoreActivity activity, OtcBuyUI ui) {
        super.onUIReady(activity, ui);
        Intent intent = getActivity().getIntent();
        orderId = intent.getStringExtra("orderId");
        getOtcConfig();
        getOrderDetail(false, orderId);
    }

    @Override
    public void onResume() {
        super.onResume();
        startTimer();
    }

    private void startTimer() {
        timerTask = new TimerTask(){

            @Override
            public void run() {
                getOrderDetail(true,orderId);
                getMessageCount(orderId);
            }
        };
        timer = new Timer();
        timer.schedule(timerTask,OtcConstant.TIMER_DELAY,OtcConstant.TIMER_PERIOD);

    }

    public void getOtcConfig() {
        OtcApi.getConfig(new SimpleResponseListener<OtcConfigResponse>(){
            @Override
            public void onBefore() {
                super.onBefore();
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }

            @Override
            public void onSuccess(OtcConfigResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response,true)) {
                    List<OtcConfigResponse.BankBean> bankList = response.getBank();
                    if (bankList != null) {
                        getUI().showBankList(bankList);

                    }

                    getUI().showIsShowRiskTips(response.getIsShare()==1);

                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        });
    }

    private void getMessageCount(final String orderId) {
        if (!UserInfo.isLogin()) {
            return;
        }
        OtcMessageApi.messageList(orderId,"",1000,new SimpleResponseListener<OtcMessageResponse>(){
            @Override
            public void onBefore() {
                super.onBefore();
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }

            @Override
            public void onSuccess(OtcMessageResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response)) {
                    List<OtcMessageResponse.MessageBean> data = response.getArray();
                    if (data != null) {
                        if (data.size()>0) {
                            OtcMessageResponse.MessageBean messageBean = data.get(0);
                            if (messageBean != null) {
                                String id = messageBean.getId();
                                String oldMsgId = SPEx.getMsgId(orderId);
                                if (NumberUtils.sub(id,oldMsgId)>0) {
                                    getUI().showHasMessage(true);
                                }
                            }
                            return;
                        }
                    }
                    getUI().showHasMessage(false);
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        });
    }

    @Override
    public void onPause() {
        super.onPause();
        stopTimer();
    }

    private void stopTimer() {
        if (timerTask != null) {
            timerTask.cancel();
        }
        if (timer != null) {
            timer.cancel();
        }
    }

    /**
     * 获取订单详情
     * @param isAutoReq
     * @param orderId
     */
    public void getOrderDetail(final boolean isAutoReq, String orderId) {
        if (!UserInfo.isLogin()) {
            return;
        }
        if (TextUtils.isEmpty(orderId)) {
            return;
        }
        OtcOrderApi.getOrderInfo(orderId,new SimpleResponseListener<OtcOrderInfoResponse>(){

            @Override
            public void onBefore() {
                super.onBefore();
                if (!isAutoReq) {
                    getUI().showProgressDialog("","");
                }
            }

            @Override
            public void onFinish() {
                super.onFinish();
                if (!isAutoReq) {
                    getUI().dismissProgressDialog();
                }
            }

            @Override
            public void onSuccess(OtcOrderInfoResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response,true)) {
                    getUI().showOrderInfo(isAutoReq,response);
                    int status = response.getStatus();
                    //40撤销 50完全成交
                    if (status ==40||status ==50) {
                        stopTimer();
                    }
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        });

    }

    public void orderPay(OtcOrderInfoResponse.PaymentTermListBean currentPaymentBean){
        if (TextUtils.isEmpty(orderId)) {
            return;
        }
        OtcOrderApi.orderPay(orderId,currentPaymentBean.getId(),new SimpleResponseListener<ResultResponse>(){
            @Override
            public void onBefore() {
                super.onBefore();
                getUI().showProgressDialog("","");
            }

            @Override
            public void onFinish() {
                super.onFinish();
                getUI().dismissProgressDialog();
            }

            @Override
            public void onSuccess(ResultResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response,true)) {
                    getUI().showComfirmOrderPaySuccess();
                    getOrderDetail(true,orderId);
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        });
    }

    /**
     * 取消订单
     */
    public void orderCancel(){
        if (TextUtils.isEmpty(orderId)) {
            return;
        }
        OtcOrderApi.orderCancel(orderId,new SimpleResponseListener<ResultResponse>(){
            @Override
            public void onBefore() {
                super.onBefore();
                getUI().showProgressDialog("","");
            }

            @Override
            public void onFinish() {
                super.onFinish();
                getUI().dismissProgressDialog();
            }

            @Override
            public void onSuccess(ResultResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response,true)) {
                    getUI().showCancelOrderSuccess();
                    stopTimer();
                    getOrderDetail(true,orderId);
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        });
    }

    public void getOrderPengList() {
        OtcOrderApi.getOrderPendingList(new SimpleResponseListener<OrderPendingListResponse>(){
            @Override
            public void onBefore() {
                super.onBefore();
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }

            @Override
            public void onSuccess(OrderPendingListResponse response) {
                super.onSuccess(response);
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        });
    }

    /**
     * 获取待处理订单个数
     */
    public void getOrderPengListCount(){

        OtcOrderApi.getOrderPendingCount(new SimpleResponseListener<OrderPendingCountResponse>(){
            @Override
            public void onBefore() {
                super.onBefore();
            }

            @Override
            public void onFinish() {
                super.onFinish();
            }

            @Override
            public void onSuccess(OrderPendingCountResponse response) {
                super.onSuccess(response);
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        });
    }
}
